using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Services;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoCompleteFornecedor : WebService
{
    string connectionString = "Data Source=LEONALDO-PC;Initial Catalog=BD_SisVenda;Integrated Security=True;MultipleActiveResultSets=True";
    public AutoCompleteFornecedor()
    {
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        DataView data = GetData();
        data = FilterData(data, prefixText);

        int totalCount = data.Count;
        if (data.Count > count)
            totalCount = count;
        string[] suggestions = new string[totalCount];

        int i = 0;
        foreach (DataRowView row in data)
        {
            suggestions[i++] = (string)row["Nome"];
            if (i >= count)
                break;
        }

        return suggestions;
    }

    private DataView GetData()
    {
        DataView view = (DataView)HttpContext.Current.Cache["AutoCompleteFornecedor"];
        if (view == null)
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Pessoa WHERE TipoPessoa LIKE 'J'", connectionString);
            DataTable table = new DataTable();
            adapter.Fill(table);
            view = table.DefaultView;

            HttpContext.Current.Cache["AutoCompleteFornecedor"] = view;
        }

        return view;
    }

    private DataView FilterData(DataView view, string prefix)
    {
        view.RowFilter = String.Format("Nome LIKE '{0}%'", prefix);
        return view;
    }
}
